<template>
  <form role="form" action="" method="post" class="registration-form">
    <div class="form-group">
      <label class="sr-only" for="form-name">User name</label>
      <input type="text" v-model="username" placeholder="Username..." class="form-first-name form-control" id="form-name">
    </div>
    <div class="form-group">
      <label class="sr-only" for="form-password">Password</label>
      <input type="text" v-model="password" placeholder="Password..." class="form-last-name form-control" id="form-password">
    </div>
    <!--注册-->
    <div v-if="register">
      <div class="form-group">
        <label class="sr-only" for="form-password2">Password</label>
        <input type="text" name="form-email" placeholder="Password..." class="form-first-name form-control" id="form-password2">
      </div>
      <div class="form-group">
        <label class="sr-only" for="form-email">Password</label>
        <input type="text" name="form-email" placeholder="Email" class="form-email form-control" id="form-email">
      </div>
    </div>
    <button type="button" id="submit" class="btn">{{btnName}} !</button>
    <label style="color:#f00; padding-left: 20px; font-weight: normal">{{errorMsg}}</label>
  </form>
</template>

<script>
import * as Util from '../js/util';

export default {
  name: 'login',
  components: {
  },
  data () {
    return {
      register: 0, // 0 - Login， 1 - Register
      btnName: 'Login',
      username: '',
      password: '',
      errorMsg: ''
    }
  },
  mounted: function () {
    $('.registration-form input[type="text"], .registration-form textarea').on('focus', function() {
      $(this).removeClass('input-error');
    });
    let $this = this;
    $('#submit').on('click', function (e) {
      let flag = true;
      $(this).find('input[type="text"], textarea').each(function () {
        if ($(this).val() === '') {
          e.preventDefault();
          $(this).addClass('input-error');
          flag = false;
        } else {
          $(this).removeClass('input-error');
          $this.errorMsg = '';
        }
      });
      if (flag) {
        $this.request();
      }
    });
  },
  methods: {
    request: function () {
      let $this = this;
      Util.ajaxData('login', {user: this.username, password: this.password}, (rst) => {
        console.log(rst);
        if (rst.status.code === 0) {
          Util.setCookie('username', rst.data.username);
          window.location.href = 'project.html';
          return;
        }
        $this.errorMsg = '用户名或密码错误！';
      });
    }
  },
  watch: {
    username: function () {
      this.errorMsg = '';
    },
    password: function () {
      this.errorMsg = '';
    }
  }
}
</script>
